package cn.turboinfo.fuyang.api.domain.admin.usecase.spec;

import cn.turboinfo.fuyang.api.domain.common.service.spec.SpecSetService;
import cn.turboinfo.fuyang.api.domain.common.usecase.AbstractUseCase;
import cn.turboinfo.fuyang.api.entity.common.pojo.spec.QSpecSet;
import cn.turboinfo.fuyang.api.entity.common.pojo.spec.Spec;
import cn.turboinfo.fuyang.api.entity.common.pojo.spec.SpecSet;
import lombok.*;
import lombok.extern.slf4j.Slf4j;
import net.sunshow.toolkit.core.qbean.api.request.QPage;
import net.sunshow.toolkit.core.qbean.api.request.QRequest;
import net.sunshow.toolkit.core.qbean.api.response.QResponse;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
@RequiredArgsConstructor
@Component
public class SpecSetSearchUseCase extends AbstractUseCase<SpecSetSearchUseCase.InputData, SpecSetSearchUseCase.OutputData> {
    private final SpecSetService specSetService;

    @Override
    protected OutputData doAction(InputData inputData) {

        QRequest request = inputData.getRequest();

        Long companyId = inputData.getCompanyId();

        if (companyId != null) {
            request.filterEqual(QSpecSet.companyId, companyId);
        }


        // 查询规格组
        QResponse<SpecSet> response = specSetService.findAll(request, inputData.getRequestPage());
        // 查询规格
        Set<Long> specSetIdSet = response.getPagedData()
                .stream()
                .map(SpecSet::getId)
                .collect(Collectors.toSet());


        List<Spec> specList = specSetService.findWithHierarchy(specSetIdSet);

        Map<Long, List<Spec>> specMap = specList.stream()
                .collect(Collectors.groupingBy(Spec::getSpecSetId));

        response.getPagedData().stream()
                .peek(it -> {
                    Long setId = it.getId();
                    if (specMap.containsKey(setId)) {

                        it.setChildren(specMap.get(setId));
                    }
                })
                .collect(Collectors.toList());

        return OutputData.builder()
                .qResponse(response)
                .build();
    }

    @EqualsAndHashCode(callSuper = true)
    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    @Builder
    public static class InputData extends AbstractUseCase.InputData {

        private Long companyId;

        private QRequest request;

        private QPage requestPage;

    }

    @Getter
    @Setter
    @Builder
    public static class OutputData extends AbstractUseCase.OutputData {
        private QResponse<SpecSet> qResponse;
    }
}
